<?php

namespace Code;

class Model
{

    private $host;
    private $db;
    private $user;
    private $pass;

    private function __construct($host, $db, $user, $pass) {
        $this->host = $host;
        $this->db = $db;
        $this->user = $user;
        $this->pass = $pass;
        return $this;
    }

    public static function getInstance() {
        static $instance = null;
        if (is_null($instance)) {
            if (func_num_args()==4) {
                $instance = new Model(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3));
            }
        }
        return $instance;
    }

    public function connect() {
        $connection_handler = mysql_connect($this->host, $this->user, $this->pass);
        if (!$connection_handler) {
            return false;
        }
        $db_handler = mysql_select_db($this->db, $connection_handler);
        if (!$db_handler) {
            return false;
        }
        return $connection_handler;
    }

    public function close($handler=null) {
        if (is_null($handler)) {
            return mysql_close();
        } else {
            return mysql_close($handler);
        }
    }

    public function query($query) {
        $connection_handler = $this->connect();
        $result = mysql_query($query, $connection_handler);
        if ($result && preg_match('/insert into/i', $query)) {
            $result = mysql_insert_id();
        }
        $this->close($connection_handler);
        return $result;
    }

    public function fetchAll($result, $as = 'array') {
        if (!$result) {
            return false;
        }
        $connection_handler = $this->connect();
        $array = array();
        if ($as == 'object') {
            while ( $row = mysql_fetch_object($result) ) {
                $array[] = $row;
            }
        } else {
            while ( $row = mysql_fetch_assoc($result) ) {
                $array[] = $row;
            }
        }
        $this->close($connection_handler);
        return $array;
    }

    public function fetchOne($result, $as = 'array') {
        if (!$result) {
            return false;
        }
        $connection_handler = $this->connect();
        if ($as == 'object') {
            $row = mysql_fetch_object($result);
        } else {
            $row = mysql_fetch_assoc($result);
        }
        $this->close($connection_handler);
        return $row;
    }

    public function numRows($result) {
        if (!$result) {
            return 0;
        } else {
            return mysql_num_rows($result);
        }
    }

}

?>
